package org.boticelli.plugin.chat;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.boticelli.Bot;
import org.springframework.util.Assert;


public class ChatBotEntry
{
    protected static Logger log = Logger.getLogger(ChatBotEntry.class);

    private List<ChatMessage> messages;
    private Bot bot;
    private long lastAccess;

    public ChatBotEntry(Bot bot)
    {
        Assert.notNull(bot, "bot can't be null");

        this.bot = bot;
        this.messages = new ArrayList<ChatMessage>();
    }

    public synchronized void queueMessage(ChatMessage chatMessage)
    {
        this.messages.add(chatMessage);
        this.notifyAll();
    }

    public synchronized List<ChatMessage> messages(long timeout)
    {
        if (messages.size() == 0)
        {
            try
            {
                wait(timeout);
            }
            catch (InterruptedException e)
            {
                log.info("wait for chat message interrupted",e);
            }
        }
        ArrayList<ChatMessage> copy = new ArrayList<ChatMessage>( messages);
        messages.clear();
        return copy;
    }

    public synchronized void access()
    {
        this.lastAccess = System.currentTimeMillis();
    }

    public synchronized long getLastAccess()
    {
        return lastAccess;
    }

    public void send(String message)
    {
        if (message.startsWith("/"))
        {
            String command = message.substring(1);
            if (command.startsWith("/"))
            {
                bot.say(message);
            }
            else if (command.startsWith("me"))
            {
                message = message.substring("/me".length());
                bot.sayAction(message.trim());
            }
            else
            {
                queueMessage(new ChatMessage(MessageType.INFO, "system", "unknown command "+message));
            }
        }
        else
        {
            bot.say(message);
        }
    }

    public void disconnect()
    {
        try
        {
            bot.disconnect();
        }
        catch(Exception e)
        {
            log.error("",e);
        }
    }
}
